#include "coments_manage.h"
#include "ui_coments_manage.h"
#include "adminmainwindow.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QHeaderView>
#include <QLabel>
#include <QPushButton>
#include <QRadioButton>
#include <QDateTime>
#include <QMessageBox>
#include <QButtonGroup>
#include <QTableWidgetItem>
#include <QDebug>
#include <cstdlib>  // 添加 qrand() 依赖

// Qt 5.3 不支持 QRandomGenerator，使用 qrand 替代
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
#define QRandomGenerator qrand
#endif

Coments_manage::Coments_manage(QSqlDatabase db, QWidget *parent) :
    QDialog(parent), m_db(db),
    ui(new Ui::Coments_manage)
{
    if (!m_db.isOpen()) {
            QMessageBox::critical(this, "数据库错误",
                "传入的数据库连接未打开！请检查连接传递逻辑。");
            return;
        }
    ui->setupUi(this);
    setWindowTitle("商品评论管理系统");
    resize(1000, 700);

    initUI();
    //loadSampleComments();

    loadCommentsFromDatabase();

    setupConnections();
}

Coments_manage::~Coments_manage()
{
    delete ui;
}

void Coments_manage::initUI()
{
    // 设置筛选区域
    ui->filterGroup->setTitle("评论筛选");

    // 商品筛选
    ui->productCombo->clear();
    ui->productCombo->addItem("全部商品", "");
    ui->productCombo->addItem("红玫瑰", "P001");
    ui->productCombo->addItem("百合花", "P002");
    ui->productCombo->addItem("绿萝", "P003");
    ui->productCombo->addItem("陶瓷花瓶", "P004");
    ui->productCombo->addItem("液体花肥", "P005");
    ui->productCombo->addItem("园艺剪刀", "P006");
    ui->productCombo->setMinimumWidth(150);

    // 评分筛选
    QButtonGroup *ratingGroup = new QButtonGroup(this);
    ratingGroup->addButton(ui->ratingAll);
    ratingGroup->addButton(ui->rating5);
    ratingGroup->addButton(ui->rating4);
    ratingGroup->addButton(ui->rating3);
    ratingGroup->addButton(ui->rating2);
    ratingGroup->addButton(ui->rating1);
    ui->ratingAll->setChecked(true);

    // 日期筛选 - Qt 5.3 不支持 calendarPopup 属性的直接设置方式
    ui->dateEdit->setDate(QDate::currentDate());
    ui->dateEdit->setCalendarPopup(true);  // Qt 5.3 支持此属性，但部分平台可能有差异

    // 设置表格
    ui->commentTable->setColumnCount(8);
    ui->commentTable->setHorizontalHeaderLabels({
        "ID", "商品", "用户", "评分", "评论时间", "评论内容", "状态", "管理员回复"
    });
    ui->commentTable->verticalHeader()->setVisible(false);
    ui->commentTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->commentTable->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->commentTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->commentTable->setSortingEnabled(true);

    // 设置列宽
    ui->commentTable->setColumnWidth(0, 60);   // ID
    ui->commentTable->setColumnWidth(1, 120);  // 商品
    ui->commentTable->setColumnWidth(2, 100);  // 用户
    ui->commentTable->setColumnWidth(3, 60);   // 评分
    ui->commentTable->setColumnWidth(4, 150);  // 时间
    ui->commentTable->setColumnWidth(6, 80);   // 状态
    ui->commentTable->horizontalHeader()->setSectionResizeMode(5, QHeaderView::Stretch); // Qt 5.3 使用 setResizeMode
    ui->commentTable->setColumnHidden(7, true); // 隐藏回复列

    // 详情区域
    ui->commentLabel->setWordWrap(true);
    ui->commentLabel->setStyleSheet("background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px; padding: 10px;");
    ui->commentLabel->setMinimumHeight(80);

    ui->adminReply->setPlaceholderText("在此输入回复内容...");
    ui->adminReply->setMinimumHeight(100);
    ui->adminReply->setStyleSheet("border: 1px solid #dee2e6; border-radius: 4px; padding: 5px;");

    ui->statusLabel->setStyleSheet("color: red; font-weight: bold;");
    ui->statusLabel->setText("未回复");

    ui->replyButton->setIcon(QIcon(":/icons/reply.png"));
    ui->replyButton->setStyleSheet("padding: 8px 15px; background-color: #4CAF50; color: white;");
}

void Coments_manage::setupConnections()
{
    // 筛选变化 - 使用 Qt 5.3 兼容的信号槽语法
    connect(ui->productCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(applyFilters()));
    connect(ui->ratingAll, SIGNAL(clicked()), this, SLOT(applyFilters()));
    connect(ui->rating5, SIGNAL(clicked()), this, SLOT(applyFilters()));
    connect(ui->rating4, SIGNAL(clicked()), this, SLOT(applyFilters()));
    connect(ui->rating3, SIGNAL(clicked()), this, SLOT(applyFilters()));
    connect(ui->rating2, SIGNAL(clicked()), this, SLOT(applyFilters()));
    connect(ui->rating1, SIGNAL(clicked()), this, SLOT(applyFilters()));
    connect(ui->unreadCheck, SIGNAL(stateChanged(int)), this, SLOT(applyFilters()));
    connect(ui->repliedCheck, SIGNAL(stateChanged(int)), this, SLOT(applyFilters()));
    connect(ui->dateEdit, SIGNAL(dateChanged(QDate)), this, SLOT(applyFilters()));
    connect(ui->resetButton, SIGNAL(clicked()), this, SLOT(resetFilters()));

    // 评论选择
    connect(ui->commentTable, SIGNAL(itemSelectionChanged()), this, SLOT(showCommentDetail()));

    // 提交回复
    connect(ui->replyButton, SIGNAL(clicked()), this, SLOT(submitReply()));
}

void Coments_manage::resetFilters()
{
    ui->productCombo->setCurrentIndex(0);
    ui->ratingAll->setChecked(true);
    ui->unreadCheck->setChecked(false);
    ui->repliedCheck->setChecked(false);
    ui->dateEdit->setDate(QDate()); // 设置为空日期

    // 确保所有行可见
    for (int row = 0; row < ui->commentTable->rowCount(); ++row) {
        ui->commentTable->setRowHidden(row, false);
    }
}

void Coments_manage::applyFilters() {
    QString productFilter = ui->productCombo->currentData().toString();
    QString productNameFilter = ui->productCombo->currentText();

    // 处理"全部商品"选项
    if (productNameFilter == "全部商品") {
        productFilter = "";
    }

    int ratingFilter = -1; // -1 表示所有评分
    if (ui->rating5->isChecked()) {
        ratingFilter = 5;
    } else if (ui->rating4->isChecked()) {
        ratingFilter = 4;
    } else if (ui->rating3->isChecked()) {
        ratingFilter = 3;
    } else if (ui->rating2->isChecked()) {
        ratingFilter = 2;
    } else if (ui->rating1->isChecked()) {
        ratingFilter = 1;
    } else {
        ratingFilter = -1;
    }

    bool unreadFilter = ui->unreadCheck->isChecked();
    bool repliedFilter = ui->repliedCheck->isChecked();
    QDate dateFilter = ui->dateEdit->date();

    // 调试输出当前筛选条件
    qDebug() << "应用筛选 - 商品ID:" << productFilter
             << " 商品名称:" << productNameFilter
             << " 评分:" << ratingFilter
             << " 未回复:" << unreadFilter
             << " 已回复:" << repliedFilter
             << " 日期:" << dateFilter.toString("yyyy-MM-dd");

    // 先显示所有行
    for (int row = 0; row < ui->commentTable->rowCount(); ++row) {
        ui->commentTable->setRowHidden(row, false);
    }

    // 如果没有选择任何筛选条件，直接返回
    if (productFilter.isEmpty() && ratingFilter == -1 &&
        !unreadFilter && !repliedFilter && dateFilter.isNull()) {
        return;
    }

    // 遍历所有行应用筛选
    for (int row = 0; row < ui->commentTable->rowCount(); ++row) {
        bool match = true;

        // 1. 商品筛选
        if (!productFilter.isEmpty() && match) {
            QTableWidgetItem* productItem = ui->commentTable->item(row, 1);
            if (productItem) {
                QString productId = productItem->data(Qt::UserRole).toString();
                QString productName = productItem->text();

                bool idMatch = (productId == productFilter);
                bool nameMatch = (productName == productNameFilter);

                if (!idMatch && !nameMatch) {
                    match = false;
                }
            } else {
                match = false;
            }
        }

        // 2. 评分筛选
        if (ratingFilter != -1 && match) {
            QTableWidgetItem* ratingItem = ui->commentTable->item(row, 3);
            if (ratingItem) {
                QString ratingText = ratingItem->text();
                int commentRating = ratingText.remove("★").toInt();

                if (commentRating != ratingFilter) {
                    match = false;
                }
            } else {
                match = false;
            }
        }

        // 3. 状态筛选
        if (match && (unreadFilter || repliedFilter)) {
            QTableWidgetItem* statusItem = ui->commentTable->item(row, 6);
            if (statusItem) {
                QString status = statusItem->text();

                if (!(unreadFilter && repliedFilter)) {
                    if (unreadFilter && status != "未回复") {
                        match = false;
                    } else if (repliedFilter && status != "已回复") {
                        match = false;
                    }
                }
            } else {
                match = false;
            }
        }

        // 4. 日期筛选
        if (match && !dateFilter.isNull()) {
            QTableWidgetItem* dateItem = ui->commentTable->item(row, 4);
            if (dateItem && !dateItem->text().isEmpty()) {
                QString dateText = dateItem->text();
                QDate commentDate = QDate::fromString(dateText, "yyyy-MM-dd");

                if (commentDate.isValid()) {
                    if (commentDate != dateFilter) {
                        match = false;
                    }
                } else {
                    match = false;
                }
            } else {
                match = false;
            }
        }

        // 隐藏不匹配的行
        ui->commentTable->setRowHidden(row, !match);
    }
}

void Coments_manage::showCommentDetail()
{
    QList<QTableWidgetItem*> items = ui->commentTable->selectedItems();
    if (items.isEmpty()) return;

    int row = items.first()->row();
    currentCommentId = ui->commentTable->item(row, 0)->text();
    ui->commentLabel->setText(ui->commentTable->item(row, 5)->text());
    ui->adminReply->setPlainText(ui->commentTable->item(row, 7)->text());

    // 更新状态显示
    if (!ui->adminReply->toPlainText().isEmpty()) {
        ui->statusLabel->setText("已回复");
        ui->statusLabel->setStyleSheet("color: green; font-weight: bold;");
        ui->replyButton->setText("更新回复");
    } else {
        ui->statusLabel->setText("未回复");
        ui->statusLabel->setStyleSheet("color: red; font-weight: bold;");
        ui->replyButton->setText("提交回复");
    }
}

void Coments_manage::submitReply()
{
    QString reply = ui->adminReply->toPlainText().trimmed();
    if (reply.isEmpty()) {
        QMessageBox::warning(this, "回复不能为空", "请填写回复内容后再提交");
        return;
    }

    // 更新数据库
    QSqlQuery query(m_db);
    query.prepare("UPDATE Comments SET reply = :reply, status = '已回复' WHERE comment_id = :comment_id");
    query.bindValue(":reply", reply);
    query.bindValue(":comment_id", currentCommentId.toInt());

    if (!query.exec()) {
        QMessageBox::critical(this, "数据库错误",
            QString("无法保存回复:\n%1\n\nSQL语句:\n%2")
            .arg(query.lastError().text())
            .arg(query.lastQuery()));
        return;
    }

    int rowsAffected = query.numRowsAffected();
    if (rowsAffected == 0) {
        QMessageBox::warning(this, "更新失败",
            QString("未找到评论ID为 %1 的记录").arg(currentCommentId));
        return;
    }

    // 刷新界面状态
    ui->statusLabel->setText("已回复");
    ui->statusLabel->setStyleSheet("color: green; font-weight: bold;");
    ui->replyButton->setText("更新回复");

    QMessageBox::information(this, "操作成功",
        QString("回复已成功提交并保存到数据库！\n评论ID: %1").arg(currentCommentId));

    // 重新加载评论列表
    loadCommentsFromDatabase();
}

void Coments_manage::loadSampleComments()
{
    QStringList products = {"玫瑰礼盒", "百合花束", "康乃馨花篮", "郁金香花束", "向日葵花束"};
    QStringList users = {"张伟", "李芳", "王明", "刘洋", "陈静", "赵强", "周婷"};

    QDateTime current = QDateTime::currentDateTime();

    for (int i = 1; i <= 20; ++i) {
        int row = ui->commentTable->rowCount();
        ui->commentTable->insertRow(row);

        // ID
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(1000 + i));
        idItem->setTextAlignment(Qt::AlignCenter);
        ui->commentTable->setItem(row, 0, idItem);

        // 商品
        // Qt 5.3 不支持 QRandomGenerator::global()，使用 qrand 替代
        int productIdx = qrand() % products.size();
        QTableWidgetItem *productItem = new QTableWidgetItem(products[productIdx]);
        productItem->setData(Qt::UserRole, "P00" + QString::number(productIdx + 1));
        ui->commentTable->setItem(row, 1, productItem);

        // 用户
        int userIdx = qrand() % users.size();
        QTableWidgetItem *userItem = new QTableWidgetItem(users[userIdx]);
        ui->commentTable->setItem(row, 2, userItem);

        // 评分 (4-5星为主)
        int rating = qrand() % 5 + 1;
        if (qrand() % 10 < 7)
            rating = qrand() % 2 + 4; // 70% 4-5星

        QTableWidgetItem *ratingItem = new QTableWidgetItem(QString::number(rating) + "★");
        ratingItem->setData(Qt::UserRole, rating);
        ratingItem->setTextAlignment(Qt::AlignCenter);
        if (rating >= 4) ratingItem->setForeground(Qt::darkGreen);
        else if (rating == 3) ratingItem->setForeground(QColor(255, 165, 0));
        else ratingItem->setForeground(Qt::red);
        ui->commentTable->setItem(row, 3, ratingItem);

        // 时间
        QDateTime time = current.addDays(-(qrand() % 30));
        QTableWidgetItem *timeItem = new QTableWidgetItem(time.toString("yyyy-MM-dd hh:mm"));
        timeItem->setTextAlignment(Qt::AlignCenter);
        ui->commentTable->setItem(row, 4, timeItem);

        // 评论内容
        QStringList comments = {
            "花束非常漂亮，包装精美，女朋友很喜欢！",
            "送货速度很快，花很新鲜，下次还会购买。",
            "性价比很高，比实体店便宜不少。",
            "花的质量一般，有几朵已经蔫了。",
            "包装很精致，服务态度很好，点赞！",
            "花没有图片上那么新鲜，有点失望。",
            "非常满意，朋友生日收到后很开心！",
            "物流太慢了，花送到的时候已经不太新鲜了。",
            "花束搭配得很好看，香味也很迷人。",
            "客服态度很好，解决了我的问题。"
        };
        int commentIdx = qrand() % comments.size();
        QTableWidgetItem *commentItem = new QTableWidgetItem(comments[commentIdx]);
        ui->commentTable->setItem(row, 5, commentItem);

        // 状态
        bool replied = (qrand() % 4) != 0; // 75% 已回复
        QTableWidgetItem *statusItem = new QTableWidgetItem(replied ? "已回复" : "未回复");
        statusItem->setTextAlignment(Qt::AlignCenter);
        statusItem->setForeground(replied ? Qt::darkGreen : Qt::red);
        ui->commentTable->setItem(row, 6, statusItem);

        // 管理员回复
        QStringList replies = {
            "感谢您的支持，我们会继续努力提供更好的服务！",
            "很抱歉给您带来不便，我们会改进物流配送服务。",
            "谢谢您的反馈，我们会提高花材品质。",
            "很高兴您喜欢我们的花束，期待再次为您服务！",
            "我们会将您的意见反馈给相关部门进行改进。",
            "感谢您选择我们，祝您生活愉快！",
            ""
        };
        QTableWidgetItem *replyItem = new QTableWidgetItem(replied ? replies[qrand() % (replies.size()-1)] : "");
        ui->commentTable->setItem(row, 7, replyItem);
    }
}

void Coments_manage::loadCommentsFromDatabase()
{
    ui->commentTable->clearContents();
    ui->commentTable->setRowCount(0);

    // SQL查询语句
    QString sql = "SELECT "
                  "c.comment_id, "
                  "p.name AS product_name, "
                  "p.product_id, "
                  "u.username, "
                  "c.rating, "
                  "c.create_time, "
                  "c.content, "
                  "c.status, "
                  "c.reply AS admin_reply "
                  "FROM Comments c "
                  "INNER JOIN login_users u ON c.user_id = u.user_id "
                  "INNER JOIN products p ON c.product_id = p.product_id "
                  "ORDER BY c.create_time DESC";

    QSqlQuery query(m_db);
    if (!query.exec(sql)) {
        QMessageBox::critical(this, "查询失败",
            QString("SQL错误：%1\n\nSQL语句：%2")
            .arg(query.lastError().text())
            .arg(sql));
        return;
    }

    // 检查是否有数据
    if (!query.first()) {
        QMessageBox::information(this, "提示", "暂无评论数据");
        return;
    }
    query.previous();

    // 遍历查询结果
    while (query.next()) {
        int row = ui->commentTable->rowCount();
        ui->commentTable->insertRow(row);

        // 1. 评论ID
        QTableWidgetItem *idItem = new QTableWidgetItem(query.value("comment_id").toString());
        idItem->setTextAlignment(Qt::AlignCenter);
        ui->commentTable->setItem(row, 0, idItem);

        // 2. 商品名称
        QTableWidgetItem *productItem = new QTableWidgetItem(query.value("product_name").toString());
        productItem->setData(Qt::UserRole, query.value("product_id").toString());
        ui->commentTable->setItem(row, 1, productItem);

        // 3. 用户名
        QTableWidgetItem *userItem = new QTableWidgetItem(query.value("username").toString());
        ui->commentTable->setItem(row, 2, userItem);

        // 4. 评分
        int rating = query.value("rating").toInt();
        QTableWidgetItem *ratingItem = new QTableWidgetItem(QString::number(rating) + "★");
        ratingItem->setData(Qt::UserRole, rating);
        ratingItem->setTextAlignment(Qt::AlignCenter);
        if (rating >= 4) ratingItem->setForeground(Qt::darkGreen);
        else if (rating == 3) ratingItem->setForeground(QColor(255, 165, 0));
        else ratingItem->setForeground(Qt::red);
        ui->commentTable->setItem(row, 3, ratingItem);

        // 5. 评论时间
        QString dateStr = query.value("create_time").toString();
        QDate commentDate = QDate::fromString(dateStr, "yyyy-MM-dd");

        QTableWidgetItem *timeItem = new QTableWidgetItem(
            commentDate.isValid() ?
            commentDate.toString("yyyy-MM-dd") :
            "日期格式错误"
        );
        timeItem->setTextAlignment(Qt::AlignCenter);
        ui->commentTable->setItem(row, 4, timeItem);

        // 6. 评论内容
        QTableWidgetItem *contentItem = new QTableWidgetItem(query.value("content").toString());
        ui->commentTable->setItem(row, 5, contentItem);

        // 7. 状态
        QString status = query.value("status").toString();
        QTableWidgetItem *statusItem = new QTableWidgetItem(status);
        statusItem->setTextAlignment(Qt::AlignCenter);
        statusItem->setForeground(status == "已回复" ? Qt::darkGreen : Qt::red);
        ui->commentTable->setItem(row, 6, statusItem);

        // 8. 管理员回复
        QTableWidgetItem *replyItem = new QTableWidgetItem(query.value("admin_reply").toString());
        ui->commentTable->setItem(row, 7, replyItem);
    }

    qDebug() << "成功加载" << ui->commentTable->rowCount() << "条评论数据";
}

void Coments_manage::on_pushButton_clicked()
{
    QWidget *parentWidget = qobject_cast<QWidget*>(parent());
    if (parentWidget) {
        parentWidget->show();
    } else {
        adminMainWindow *m = new adminMainWindow(m_db);
        m->setAttribute(Qt::WA_DeleteOnClose);
        m->show();
    }
    this->close();
}
